function onsets = bciP3Synchronize(bci, trig, resp, prm, evt,N)

if ~bci.param.doReceiveTrigger,
    onsets = round(prm.flashOnsetTimes*bci.srate)+1;
    onsets = onsets(sum(prm.flashSequenceMat(:,prm.tobjIdx,N),2)>0);
    return
end

trig = removeRepeatedTrigger(trig,3);
resp = removeRepeatedTrigger(resp,3);

trigIdx = find(trig==bci.paradigm.flashSyncTrigger);
respIdx = find(resp==1|resp==2);

if isfield(prm,'positionMat'),
    targetEvt = prm.positionMat(:,N)==evt;
else
    targetEvt = evt;
end

flashSequenceMat = prm.flashSequenceMat(:,prm.tobjIdx,N);
flashSequenceMat(sum(flashSequenceMat,2)==0,:)=[];
destSequence = flashSequenceMat(:,targetEvt)>0;

if length(respIdx) ~=sum(destSequence),
    warning('Number of synchronization  flashes = %i.\nIgnoring missing flash cue.',length(respIdx));
end
nFlashes = prm.nObjects*bci.paradigm.nTargetFlashes;

if length(trigIdx) ~= nFlashes,
    warning('Number of synchronization  trigger = %i.\nNegleting trigger delay.',length(trigIdx));
    onsets = round(prm.flashOnsetTimes*bci.srate)+1;
    trigIdx = onsets(sum(prm.flashSequenceMat(:,prm.tobjIdx,N),2)>0)+30;% add estimate of flash delay
end

targetFlashPos = trigIdx(destSequence);
flashDelay = zeros(size(respIdx));
for k=1:length(respIdx),
    flashDelays = respIdx(k)-targetFlashPos;
    flashDelay(k) = min(flashDelays(flashDelays>0));
end

if std(flashDelay)>0.1*bci.srate,
    warning('High deviations in trigger synchronization detected.');
end

flashDelay = round(mean(flashDelay));

onsets=trigIdx+flashDelay;
